package org.laobai.permission.interceptor;

import org.laobai.permission.config.UserThreadLocal;
import org.laobai.permission.entity.User;
import org.laobai.permission.util.Asserts;
import org.laobai.permission.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author jiusan
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private UserThreadLocal userThreadLocal;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }

        String token = request.getHeader("token");
        Asserts.isNotNull(token, 50004, "用户未登录");
        User user = jwtUtils.getUserFromToken(token);

        Asserts.assertTrue(Objects.nonNull(user), 50004, "用户未登录");
        // 存入threadLocal
        userThreadLocal.setUser(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        userThreadLocal.removeUser();
    }
}
